/* eslint-disable max-lines */
/* eslint-disable no-nested-ternary */
import React from 'react';
import routes from './routes';
import {getDetail} from './api';
import styles from './style.css';
import PropTypes from 'prop-types';
import Return from '../common/Return';
import FileUpload from './FileUpload';
import {ListTypeCL, dataTimeDay} from './utils';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl, language, formatMessage} from './intl';
import WrappedDatePicker from '../common/WrappedDatePicker';
import SaleConfirmationSelect from './SaleConfirmationSelect';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import {saleOrderTransportType, declarePlace, declareType} from '../Enum';
import {formatDateTime, conventEnumValueToString} from '../utils';
import {FORM_OPTIONS, DATE_FORMAT, TABLE, FILES_API, FIXED_COLUMN_WIDTH} from '../constants';
import {Spin, Card, Button, Form, Row, Col, Input, Table, Popconfirm} from 'antd';
const FormItem = Form.Item;
const {Description} = DescriptionList;
const declareTypeList = declareType.toList(language);
const declarePlaceList = declarePlace.toList(language);
const saleOrderTransportTypeList = saleOrderTransportType.toList(language);
class NewPanel extends React.PureComponent {
    state = {
        data: {
            attachments: []
        },
        details: [],
        loading: false,
        hasOperat: false,
        isValidate: false,
        showSaleConfirmation: false
    }
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    getDetailInfo = () => {
        this.setState(({loading: true}));
        getDetail(this.props.id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data.details,
                        details: res.data.details.details,
                        attachments: res.data.details.attachments
                    });
                else
                    this.setState(({loading: false}));
            });
    }
    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onSelectDealer = (condition = {}) => {
        const data = Object.assign({}, this.state.data, {
            dealerId: condition.id,
            dealerCode: condition.code,
            dealerName: condition.name,
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    
    onClickAdd = () => {
        const {data, details} = this.state;
        const {initEnumData} = this.props;
        const isValid = newOrUpdateOrderValidator(data, details, '', initEnumData.brands);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({showSaleConfirmation: true});
    }
    onCloseAdd = () => this.setState({showSaleConfirmation: false});
    onSaleConfirmation = records => {
        const details = this.state.details || [];
        if(records && records.length > 0)
            // eslint-disable-next-line array-callback-return
            records.map(item => {
                const index = details.findIndex(v => v.saleConfirmationId === item.id);
                if(index === -1)
                    details.push({
                        saleDeliveryOrderDetailId: item.saleDeliveryOrderDetailId,
                        saleDeliveryOrderId: item.saleDeliveryOrderId,
                        saleDeliveryOrderCode: item.saleDeliveryOrderCode,
                        saleConfirmationId: item.id,
                        saleConfirmationrCode: item.code,
                        productId: item.productId,
                        productCode: item.productCode,
                        productName: item.productName,
                        quantity: item.quantity,
                        price: item.price,
                        vin: item.vin,
                        totalPrice: item.totalPrice
                    });
                
                this.setState({
                    details: [...details],
                    hasOperat: true,
                    showSaleConfirmation: false
                });
            });
        else
            this.setState({
                details: [...details],
                hasOperat: true,
                showSaleConfirmation: false
            });
    }
    onDeletePart = e => {
        const Id = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.saleConfirmationId !== Id);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onSubmit = () => {
        const {data, details} = this.state;
        const {initEnumData} = this.props;
        const isValid = newOrUpdateOrderValidator(data, details, 'type', initEnumData.brands);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(this.props.types, data, details, initEnumData.brands).then(res => {
            if(res.success)
                this.props.successReturn();
            this.setState({loading: false});
        });
    };
    render() {
        const {types, initEnumData} = this.props;
        const {data, details, validate, loading, hasOperat} = this.state;
        const currentSelectRowkeys = details.map(item => item.saleDeliveryOrderDetailId);
        const validateBrands = !data.brandId && validate ? 'error' : null;
        const validateDealer = !data.dealerId && validate ? 'error' : null;
        const validateTransportType = !data.transportType && validate ? 'error' : null;
        const validateExpectDepartedDate = !data.expectDepartedDate && validate ? 'error' : null;
        const editAuthority = types === 'signned' || types === 'dateSupplement';
        const addAuthority = types === 'add' || types === 'update';
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const columns = [{
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.colums.saleConfirmationrCode',
                defaultMessage: '销售确认书编号'
            })}</span>,
            dataIndex: 'saleConfirmationrCode'
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.colums.saleDeliveryOrderCode',
                defaultMessage: '交货单编号'
            })}</span>,
            dataIndex: 'saleDeliveryOrderCode'
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.colums.productCode',
                defaultMessage: '物料号'
            })}</span>,
            dataIndex: 'productCode'
        }, {
            title: formatMessage({
                id: 'newPanel.colums.productName',
                defaultMessage: '物料名称'
            }),
            dataIndex: 'productName'
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.colums.vin',
                defaultMessage: 'VIN'
            })}</span>,
            dataIndex: 'vin'
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'newPanel.colums.quantity',
                defaultMessage: '数量'
            })}</span>,
            dataIndex: 'quantity'
        }, {
            title: formatMessage({
                id: 'newPanel.colums.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price'
        }, {
            title: formatMessage({
                id: 'newPanel.colums.totalPrice',
                defaultMessage: '总价'
            }),
            dataIndex: 'totalPrice'
        }];
        if(!editAuthority)
            columns.push({
                title: details && details.length > 0
                    ? (
                        <Popconfirm placement="topRight" title={formatMessage({
                            id: 'newPanel.column.allDelete',
                            defaultMessage: '是否确认全部删除？'
                        })} onConfirm={this.onDeleteAll} >
                            <a>{formatMessage({
                                id: 'newPanel.column.empty',
                                defaultMessage: '清空'
                            })}</a>
                        </Popconfirm>
                    )
                    : <a>{formatMessage({
                        id: 'newPanel.column.empty',
                        defaultMessage: '清空'
                    })}</a>,
                dataIndex: 'saleConfirmationId',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => <a data-id={text} onClick={this.onDeletePart}>删除</a>
            });
        return (
            <div className="form-standard">
                <Spin spinning={loading}>
                    <Card title={formatMessage({
                        id: 'newPanel.column.common',
                        defaultMessage: '整车发运信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.code',
                                        defaultMessage: '发运单号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {types === 'add'
                                            ? <Input placeholder={formatMessage({
                                                id: 'newPanel.form.notGenerate',
                                                defaultMessage: '尚未生成'
                                            })}
                                            disabled />
                                            : data.code}
                                    </FormItem>
                                </Col>
                                {initEnumData.brands && initEnumData.brands.length > 1 &&
                                 <Col {...FORM_OPTIONS.col}>
                                     <FormItem label={formatMessage({
                                         id: 'newPanel.form.brandName',
                                         defaultMessage: '品牌'
                                     })} {...FORM_OPTIONS.item} validateStatus={validateBrands} required={addAuthority}>
                                         {editAuthority
                                             ? `${data.brandCode}(${data.brandName})`
                                             : <WrappedSelect
                                                 allowClear
                                                 name="brandId"
                                                 value={data.brandId}
                                                 options={initEnumData.brands}
                                                 onChange={this.handleFilterChange}/>}
                                     </FormItem>
                                 </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDealer} required={addAuthority}>
                                        {editAuthority
                                            ? `${data.dealerCode}(${data.dealerName})`
                                            : <DealerSelectPanel
                                                value={dealerInfo}
                                                onChange={this.handleFilterChange}
                                                onSelect={this.onSelectDealer} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.batchNumber',
                                        defaultMessage: '批次号'
                                    })} {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? data.batchNumber
                                            : <TextInput
                                                name="batchNumber"
                                                value={data.batchNumber}
                                                onBlur={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.transportType',
                                            defaultMessage: '运输方式'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateTransportType} required={addAuthority}>
                                        {editAuthority
                                            ? conventEnumValueToString(saleOrderTransportType, data.transportType)
                                            : <WrappedSelect
                                                allowClear
                                                name="transportType"
                                                value={data.transportType}
                                                options={saleOrderTransportTypeList}
                                                onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.origin',
                                        defaultMessage: '起运地'
                                    })} {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? data.origin
                                            : <TextInput
                                                name="origin"
                                                value={data.origin}
                                                onBlur={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.destination',
                                        defaultMessage: '目的地'
                                    })} {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? data.destination
                                            : <TextInput
                                                name="destination"
                                                value={data.destination}
                                                onBlur={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.expectShipmentDate',
                                            defaultMessage: '预计发运日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? formatDateTime(data.expectShipmentDate, DATE_FORMAT)
                                            : <WrappedDatePicker
                                                name="expectShipmentDate"
                                                value={data.expectShipmentDate}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.actualShipmentDate',
                                            defaultMessage: '实际发运日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {types === 'signned'
                                            ? formatDateTime(data.actualShipmentDate, DATE_FORMAT)
                                            : <WrappedDatePicker
                                                name="actualShipmentDate"
                                                value={data.actualShipmentDate}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.expectDepartedDate',
                                            defaultMessage: '预计离港日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        helpShow validateStatus={validateExpectDepartedDate} required={addAuthority}>
                                        {editAuthority
                                            ? formatDateTime(data.expectDepartedDate, DATE_FORMAT)
                                            : <WrappedDatePicker
                                                name="expectDepartedDate"
                                                value={data.expectDepartedDate}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.expectArrivalDate',
                                            defaultMessage: '预计到港日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? formatDateTime(data.expectArrivalDate, DATE_FORMAT)
                                            : <WrappedDatePicker
                                                name="expectArrivalDate"
                                                value={data.expectArrivalDate}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.expectShipmentDay',
                                            defaultMessage: '预计发运天数'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {dataTimeDay(data.expectArrivalDate, data.expectDepartedDate)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.actualDepartedDate',
                                            defaultMessage: '实际离港日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? formatDateTime(data.actualDepartedDate, DATE_FORMAT)
                                            : <WrappedDatePicker
                                                name="actualDepartedDate"
                                                value={data.actualDepartedDate}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.actualArrivalDate',
                                            defaultMessage: '实际到港日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? formatDateTime(data.actualArrivalDate, DATE_FORMAT)
                                            : <WrappedDatePicker
                                                name="actualArrivalDate"
                                                value={data.actualArrivalDate}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.actualShipmentDay',
                                            defaultMessage: '实际发运天数'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {dataTimeDay(data.actualArrivalDate, data.actualDepartedDate)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.shipmentNumber',
                                        defaultMessage: '运输单号'
                                    })} {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? data.shipmentNumber
                                            : <TextInput
                                                name="shipmentNumber"
                                                value={data.shipmentNumber}
                                                onBlur={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.shippingCompanyAirline',
                                        defaultMessage: '船公司/航空公司'
                                    })} {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? data.shippingCompanyAirline
                                            : <TextInput
                                                name="shippingCompanyAirline"
                                                value={data.shippingCompanyAirline}
                                                onBlur={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.declarePlace',
                                            defaultMessage: '报关地点'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? conventEnumValueToString(declarePlace, data.declarePlace)
                                            : <WrappedSelect
                                                allowClear
                                                name="declarePlace"
                                                value={data.declarePlace}
                                                options={declarePlaceList}
                                                onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.declareType',
                                            defaultMessage: '报关类型'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {editAuthority
                                            ? conventEnumValueToString(declareType, data.declareType)
                                            : <WrappedSelect
                                                allowClear
                                                name="declareType"
                                                value={data.declareType}
                                                options={declareTypeList}
                                                onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.remark',
                                            defaultMessage: '备注'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {types === 'signned'
                                            ? data.remark
                                            : <TextInput
                                                name="remark" value={data.remark}
                                                onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                {types === 'signned' ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.signnedRemark',
                                            defaultMessage: '签收备注'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="signnedRemark" value={data.signnedRemark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col> : ''}
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.details',
                            defaultMessage: '整车发运单清单'
                        })}
                        extra={!editAuthority && <Button onClick={() => this.onClickAdd()} size="small">
                            {formatMessage({
                                id: 'newPanel.btn.add',
                                defaultMessage: '新增'
                            })}
                        </Button>}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="saleDeliveryOrderDetailId"
                            columns={columns}
                            pagination={false}
                            dataSource={details}
                            {...TABLE}/>
                    </Card>
                    <Card title={formatMessage({
                        id: 'newPanel.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                {editAuthority
                                    ? data.attachments.length > 0
                                        ? <DescriptionList>
                                            {data.attachments.map(item => (<Description key={item.fileId}>
                                                <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                                    {item.fileName}</a></Description>))}
                                        </DescriptionList>
                                        : <DescriptionList title={formatMessage({
                                            id: 'detailPanel.content.noAttachment',
                                            defaultMessage: '暂无附件'
                                        })} />
                                    : <FileUpload onChange={this.onChangeUpload}
                                        onRemove={this.removeFilePath}
                                        fileList={data.attachments}/>}
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Row>
                            <Col className="col-align-right">
                                <Button
                                    key="audit"
                                    loading={loading}
                                    onClick={this.onSubmit}
                                    className={styles.btnMargin}
                                    type="primary">
                                    {formatMessage({
                                        id: 'newPanel.btn.submit',
                                        defaultMessage: '提交'
                                    })}
                                </Button>
                            </Col>
                        </Row>
                    </Card>
                </Spin>
                {
                    this.state.showSaleConfirmation &&
                    <SaleConfirmationSelect
                        dealerId={data.dealerId}
                        brandId={initEnumData.brands && initEnumData.brands.length === 1 ? initEnumData.brands[0].value : data.brandId}
                        currentSelectRowkeys={currentSelectRowkeys}
                        onCancel={this.onCloseAdd}
                        onSelect={this.onSaleConfirmation} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={loading}
                        showWarning={hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnumData: PropTypes.object.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired
};

import {connect} from 'react-redux';
import {createSelector} from 'reselect';
import {querySearch, onSubmit} from './actions';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? ListTypeCL(initData.brands) : [];
        const partWarehouses = initData.partWarehouses ? ListTypeCL(initData.partWarehouses) : [];
        return {
            brands,
            partWarehouses,
            initData
        };
    }
);

const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state)
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (types, data, details, brands) => dispatch(onSubmit(types, data, details, brands)),
    successReturn: () => {
        dispatch(querySearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    }
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
